package com.zjc.gateway.filter;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;

@Configuration
public class Raonfiguration {

    /**
     * 按照手机号限流
     *
     * @return key
     */
    @Primary
    @Bean(value = "phoneKeyResolver")
    public KeyResolver phoneKeyResolver() {

        return exchange -> {
            ServerHttpRequest request = exchange.getRequest();
            MultiValueMap<String, String> m = request.getQueryParams();
            String phone = m.get("phone").toString();
            return Mono.just(phone);
        };
    }

    @Bean("loginResolver")
    public KeyResolver loginResolver() {

        return exchange -> {

            String bodyStr = getBodyJson(exchange);

            return Mono.just(bodyStr);
        };
    }

    public String getBodyJson(ServerWebExchange exchange) {
        AtomicReference<String> bodyRef = new AtomicReference<>();
        Flux<DataBuffer> body = exchange.getRequest().getBody();
        body.subscribe(buffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());
            System.out.println();
        }, System.err::println, () -> {
        });

        return bodyRef.toString();
    }
}
